<template>
  <a-modal
    :visible="visible"
    width="50vw"
    title="登录"
    @cancel="close"
    @close="handleClose"
    unmount-on-close
    :maskClosable="false"
    :escToClose="false"
  >
    <div style="display: block; text-align: center; padding: 6px 0">
      <!-- 余额不足 -->
      <template v-if="loginStatus === -99">
        <a-result status="error" title="账户余额不足，请先充值后查询违章" />
      </template>
      <!-- 未登录、登录失败、二维码过期 -->
      <template v-else-if="[0, 3, 4].includes(loginStatus)">
        <div class="qrcode-wrapper">
          <div v-if="loading" class="loading-block">
            <a-spin :loading="loading" tip="加载中..." dot />
          </div>
          <div v-else-if="loginStatus === 4" class="expired-wrapper">
            <div class="expired-qrcode">
              <div>二维码已失效</div>
              <a-button type="outline" size="mini" @click="getQrcode()">刷新二维码</a-button>
            </div>
            <a-image width="160" :src="iosQRCode" />
          </div>
          <a-image v-else width="160" :src="qrcodeBase64">
            <template #loader>
              <img width="160px" :src="imgLoading" />
            </template>
          </a-image>
        </div>
        <div class="tip error" v-if="loginStatus === 3"> {{ accountInfo.loginErrorMsg }} </div>
        <div class="tip" v-else> 请通过交管APP扫码登录，再查询违章 </div>

        <div class="use-tip">
          <div>扫码后请勿关闭弹窗，等待1-2分钟返回登录结果</div>
          <div> 如关闭了弹窗，请等待1-2分钟后，刷新列表查看登录状态</div>
        </div>
      </template>
    </div>

    <!-- 底部 -->
    <template #footer>
      <a-button @click="close">关闭</a-button>
    </template>
  </a-modal>
</template>

<script setup name="ViolationQueryLoginModal">
  /**
   * @step1 检验余额
   * 余额不足->结束：弹窗提示充值
   * 余额充足->@step2
   * @step2 获取账号信息
   * 账号已经登录->结束：关闭弹框打开查询弹框并刷新list数据
   * ========校验结束、进入登录流程========
   * 账号未登录->@step3 （未登录：等登录、登录失败、二维码过期）
   * @step3 获取二维码
   * 并开始 @setp4
   * @setp4 轮询获取账号信息
   *  @setp2 相同但是二维码过期时，展示刷新二维码
   */
  import { ref, computed } from 'vue'
  import { getViolationQueryBalance, getZgLoginQrcode, getQueryAccountInfo } from '@/api/asset/carViolation'
  import imgLoading from '@/assets/img-loading.png'
  import iosQRCode from '@/assets/iosQRCode_1.png'

  const emits = defineEmits(['loginSuccess', 'close'])

  const visible = ref(false)
  const record = ref({})
  const openParams = ref([])
  const open = (data, btnTypeVal) => {
    visible.value = true
    record.value = data
    openParams.value = [data, btnTypeVal]
    qrcodeBase64.value = imgLoading
    // 校验余额
    checkAccountAmount()
  }
  const close = () => {
    visible.value = false
    stopPolling()
  }

  // 校验余额
  const checkAccountAmount = () => {
    getViolationQueryBalance({ id: record.value.id }).then((res) => {
      if (res.code === 200) {
        // 余额不足
        if (res.result === false) {
          accountInfo.value.loginStatus = -99
          return
        }
        // 获取账号详情
        getAccountDetail(true)
      }
    })
  }

  // 获取二维码
  const loading = ref(false)
  const qrcodeBase64 = ref(imgLoading)
  const getQrcode = () => {
    loading.value = true
    getZgLoginQrcode({ id: record.value.id })
      .then((res) => {
        loading.value = false
        if (res.result) {
          qrcodeBase64.value = 'data:image/png;base64,' + res.result
          // 二维码过期重置为未登录状态
          if (accountInfo.value.loginStatus === 4) {
            accountInfo.value.loginStatus = 0
          }
          // 开始轮询
          startPolling()
        }
      })
      .catch((err) => {
        if (err == 'Error: 账号已登录') {
          emits('loginSuccess', ...openParams.value)
          close()
          return
        }
        accountInfo.value.loginStatus = 4
        setTimeout(() => {
          loading.value = false
        }, 900)
      })
  }

  // 登录状态
  const loginStatus = computed(() => accountInfo.value.loginStatus)
  // 获取账号信息
  const accountInfo = ref({
    // 0未登录，1已登录，3登录失败
    // 前端加的 -99余额不足
    loginStatus: 0,
    loginErrorMsg: '',
  })
  const getAccountDetail = (init = false) => {
    getQueryAccountInfo({ id: record.value.id }).then((res) => {
      const result = res.result
      if (res.code === 200) {
        accountInfo.value = result
        if (result.loginStatus === 1) {
          emits('loginSuccess', ...openParams.value)
          close()
        } else {
          // 初始化去获取二维码
          if (init) {
            accountInfo.value.loginStatus = 0
            getQrcode()
          }
        }
      }
    })
  }

  // 过期二维码
  // 10秒一次   轮询30次
  const POLLING_CONFIG = {
    counter: 0,
    timer: null,
    max_counter: 30, // 5分钟
    interval: 10 * 1000, // 10s
  }

  // 开始轮询
  const startPolling = () => {
    console.log('🐳 > startPolling')
    stopPolling()
    POLLING_CONFIG.timer = setInterval(() => {
      console.log('🐳 > startPolling >', POLLING_CONFIG.counter)
      if (POLLING_CONFIG.counter >= POLLING_CONFIG.max_counter - 1) {
        // 二维码过期
        accountInfo.value.loginStatus = 4
        loading.value = false
        stopPolling()
        return
      }
      getAccountDetail()
      POLLING_CONFIG.counter++
    }, POLLING_CONFIG.interval)
  }
  // 停止轮询
  const stopPolling = () => {
    POLLING_CONFIG.counter = 0
    if (POLLING_CONFIG.timer) {
      clearInterval(POLLING_CONFIG.timer)
      POLLING_CONFIG.timer = null
    }
  }

  const handleClose = () => {
    emits('close')
  }

  defineExpose({
    open,
  })
</script>

<style lang="less" scoped>
  .tip {
    margin-top: 24px;
    font-weight: 500;
    font-size: 14px;
    color: #1d2129;
    line-height: 22px;
    &.error {
      color: #f53f3f;
    }
  }
  .use-tip {
    margin-top: 12px;
    font-weight: 500;
    font-size: 14px;
    color: #f53f3f;
    line-height: 22px;
  }

  .loading-block {
    width: 100%;
    height: 100%;
    border-radius: 2px;
    border: 1px solid #dcdfe6;
    padding-top: 40px;
  }

  .qrcode-wrapper {
    margin: auto;
    width: 160px;
    height: 160px;
  }

  .expired-wrapper {
    position: relative;
    .expired-qrcode {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      z-index: 999;
      background: rgba(255, 255, 255, 0.9);
      padding-top: 60px;
      // font
      font-size: 12px;
      color: #1e1e1e;
      line-height: 22px;
      margin-bottom: 6px;
    }
  }
</style>
